package com.manage.platform.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.manage.platform.service.impl.TaskAchieveServiceImpl;
import com.manage.platform.vo.CommonVo;
import com.manage.platform.vo.TaskAchieveDetailsVo;
import com.manage.platform.vo.TaskTreePartVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 组织树形结构工具类
 */
@AllArgsConstructor
@Component
public class TreeListTaskTreeOneUtil {

    private final TaskAchieveServiceImpl taskAchieveServiceImpl;

    /**
     * 构建树形结构
     * @param list 所有组织节点列表
     * @return 树形结构列表
     */
    public List<TaskTreePartVo> buildMenuTreeList(List<TaskTreePartVo> list) {
        // 使用Map缓存提高查找效率
        Map<Long, TaskTreePartVo> nodeMap = list.stream()
                .collect(Collectors.toMap(TaskTreePartVo::getId, node -> node));

        List<TaskTreePartVo> rootNodes = new ArrayList<>();

        // 构建父子关系
        for (TaskTreePartVo node : list) {
            Long parentId = node.getParentId();
            if (parentId == null || parentId.equals(0L)) {
                rootNodes.add(node);
            } else {
                TaskTreePartVo parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    //处理第三级任务，查询成果
                     if (node.getLevel() == 3) {
                         List<CommonVo> list1 = taskAchieveServiceImpl.getByTaskId(node.getId());
                         if(CollectionUtil.isNotEmpty(list1)) {
                             List<TaskTreePartVo> list2 = list1.stream().map(it -> {
                                 TaskTreePartVo treePartVo = new TaskTreePartVo();
                                 treePartVo.setId(it.getId() + 10000);
                                 treePartVo.setName(it.getName());
                                 treePartVo.setLevel(node.getLevel() + 1);
                                 treePartVo.setAnnual(node.getAnnual());
                                 treePartVo.setStatus(node.getStatus());
                                 return treePartVo;
                             }).toList();
                             node.setChildren(list2);
                         }
                     }
                    parent.getChildren().add(node);
                }
            }
        }
        return rootNodes;
    }

}
